package com.example.compiler

import java.io.OutputStream
import javax.annotation.processing.AbstractProcessor
import javax.annotation.processing.RoundEnvironment
import javax.annotation.processing.SupportedAnnotationTypes
import javax.annotation.processing.SupportedSourceVersion
import javax.lang.model.SourceVersion
import javax.lang.model.element.TypeElement
import javax.tools.Diagnostic

/**
 * 注解处理器
 */

@SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedAnnotationTypes("com.example.annotation.MyClass")
class TestProcessor : AbstractProcessor() {

    /**
     * Process javac编译时的一个回调
     *
     * @param mutableSet
     * @param roundEnvironment
     * @return
     */
    override fun process(
        mutableSet: MutableSet<out TypeElement>?,
        roundEnvironment: RoundEnvironment?
    ): Boolean {

//        roundEnvironment?.processingOver()//判断轮询是否结束
//        mutableSet?.isEmpty()//判断集合是否是空

        if (!mutableSet?.isEmpty()!!) {
            val messager = processingEnv.messager
            messager.printMessage(Diagnostic.Kind.NOTE, ">>>>>>>>>>>>>>>>>")

            val code = "public class myClass {\n" +
                    "}\n"

            val filer = processingEnv.filer
            var outputStream: OutputStream? = null
            try {
                val createClassFile = filer.createSourceFile("myClass")
                outputStream = createClassFile.openOutputStream()
                outputStream?.write(code.toByteArray())
                outputStream?.flush()
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                outputStream?.close()
            }
        }
        return false
    }


}